package com.payment.service.agatewaytobeijing;

import com.alibaba.fastjson.JSON;
import com.payment.entity.agatewaytobeijing.JsonConstant;
import com.payment.entity.agatewaytobeijing.end.request.EndRequest;
import com.payment.entity.agatewaytobeijing.end.response.EndResponse;
import com.payment.entity.agatewaytobeijing.order.RequestPurchaseService;
import com.payment.entity.agatewaytobeijing.order.request.OrderRequest;
import com.payment.entity.agatewaytobeijing.order.response.OrderResponse;
import com.payment.entity.agatewaytobeijing.querydeviceorder.request.RequestQueryDeviceOrder;
import com.payment.entity.agatewaytobeijing.querydeviceorder.response.ResponseQueryDeviceOrder;
import com.payment.utils.HMACSHA1;
import com.payment.utils.HttpUtil;
import com.payment.utils.TimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * 所有需要去请求北京企业网关的业务实现类：
 *
 * @author lm
 * @date 2020/11/6 11:48
 */
@Component
@Slf4j
public class GatewayToBeijingService {
    /**
     * 3.0接口：请求北京企业网关的地址
     */
    @Value("${jsonIot3.JSON_BASE_URL}")
    private String jsonBaseURL3;

    /**
     * 3.0接口：请求北京网关 3.16 查询套餐订单信息
     *
     * @param deviceCode
     * @param orderId
     * @param orderStatus
     * @param orderType
     * @param partnerCode
     * @param secret
     * @return
     */
    public ResponseQueryDeviceOrder queryDeviceOrder(String deviceCode, String orderId, String orderStatus, String orderType, String partnerCode, String secret) {
        RequestQueryDeviceOrder request = new RequestQueryDeviceOrder();
        request.setVersion(JsonConstant.VERSION);
        request.setTimestamp(TimeUtil.getTimeInMillis().toString());
        request.setAccess_code(partnerCode);
        request.setDevice_id(deviceCode);

        if (StringUtils.isNotBlank(orderId)) {
            request.setOrder_id(orderId);
        }
        if (StringUtils.isNotBlank(orderType)) {
            request.setOrder_type(orderType);
        }
        if (StringUtils.isNotBlank(orderStatus)) {
            request.setOrder_status(orderStatus);
        }
        request.setPage_no(1);
        request.setPage_size(1000);
        try {
            request.setSign(HMACSHA1.jsonSign(request, secret));
        } catch (Exception e) {
            log.info("计算签名出现异常：" + e);
        }
        String queryOrder = JSON.toJSONString(request);
        String response;

        if (JsonConstant.CODE_STRING_TWO.equals(orderStatus)) {
            log.info("请求查询【正在使用】订单:" + queryOrder);
            //3.0重构的接口
            String url = jsonBaseURL3 + JsonConstant.JSON_QUERY_H5_ORDER;

            // 发送post请求，并接收返回结果
            response = HttpUtil.httpPost(url, queryOrder);
            log.info("url=" + url);
            //replaceAll("\\s*|\t|\r|\n", "")):java去除字符串中的空格、回车、换行符、制表符
            log.info("响应查询【正在使用】订单：" + response.replaceAll("\\s*|\t|\r|\n", ""));
        } else if (JsonConstant.CODE_ONE.equals(orderStatus)) {
            log.info("请求查询【未启用】订单:" + queryOrder);
            //3.0重构的接口
            String url = jsonBaseURL3 + JsonConstant.JSON_QUERY_H5_ORDER;

            // 发送post请求，并接收返回结果
            response = HttpUtil.httpPost(url, queryOrder);
            log.info("url=" + url);
            //replaceAll("\\s*|\t|\r|\n", "")):java去除字符串中的空格、回车、换行符、制表符
            log.info("响应查询【未启用】订单：" + response.replaceAll("\\s*|\t|\r|\n", ""));
        } else {
            log.info("请求查询【所有】订单:" + queryOrder);
            //3.0重构的接口
            String url = jsonBaseURL3 + JsonConstant.JSON_QUERY_H5_ORDER;

            // 发送post请求，并接收返回结果
            response = HttpUtil.httpPost(url, queryOrder);
            log.info("url=" + url);
            //replaceAll("\\s*|\t|\r|\n", "")):java去除字符串中的空格、回车、换行符、制表符
            log.info("响应查询【所有】订单：" + response.replaceAll("\\s*|\t|\r|\n", ""));
        }
        //这边验证返回的是"",那么为了程序不报错给返回一个null
        if (StringUtils.isBlank(response)) {
            return null;
        }

        //这边只用验证返回的只要不是""证明请求响应是正常的
        return JSON.parseObject(response, ResponseQueryDeviceOrder.class);
    }

    /**
     * 3.0接口：请求北京网关 3.22 提前结束套餐订单  提前结束订单并且要关流量
     *
     * @param orderId
     * @param partnerCode
     * @param secret
     * @param message
     * @return
     */
    public EndResponse aheadEndOrder(String orderId, String partnerCode, String secret, String message) {
        EndRequest end = new EndRequest();
        end.setVersion(JsonConstant.VERSION);
        end.setAccess_code(partnerCode);
        end.setTimestamp(TimeUtil.getTimeInMillis().toString());
        end.setOrder_code(orderId);
        end.setAhead_finish_cause(message);
        try {
            end.setSign(HMACSHA1.jsonSign(end, secret));
        } catch (Exception e) {
            log.info("计算签名出现异常：" + e);
        }
        String requestEnd = JSON.toJSONString(end);
        log.info("请求【提前结束订单】：" + requestEnd);
        String url = jsonBaseURL3 + JsonConstant.JSON_AHEAD_FINISH_PACKAGE;
        // 发送post请求，并接收返回结果
        String response = HttpUtil.httpPost(url, requestEnd);
        log.info("url=" + url);

        log.info("响应【提前结束订单】：" + response);

        //这边验证返回的是"",那么为了程序不报错给返回一个null
        if (StringUtils.isBlank(response)) {
            return null;
        }

        return JSON.parseObject(response, EndResponse.class);
    }

    /**
     * 3.0接口：请求北京网关 3.10 订购流量套餐
     *
     * @param pur
     * @param isOpen
     * @return
     */
    public OrderResponse order(RequestPurchaseService pur, String isOpen) {
        OrderRequest order = new OrderRequest();
        order.setVersion(JsonConstant.VERSION);
        order.setAccess_code(pur.getPartnerCode());
        order.setTimestamp(TimeUtil.getTimeInMillis().toString());
        order.setDevice_id(pur.getDeviceCode());
        order.setGlobal_order("0");
        order.setPackage_name(pur.getPackageName());
        order.setPackage_code(pur.getPackageCode());
        order.setPackage_type(pur.getPackageType());
        order.setOrder_period(pur.getOrderPeriod());
        order.setPay_rst("2");
        order.setPay_type(pur.getPayType());
        order.setPay_amount(pur.getAmount());
        order.setIs_open(isOpen);
        order.setTest_flow_flag("0");

        try {
            order.setSign(HMACSHA1.jsonSign(order, pur.getSecret()));
        } catch (Exception e) {
            log.info("计算签名出现异常：" + e);
        }
        String requestOrder = JSON.toJSONString(order);
        log.info("请求【同步订购】：" + requestOrder);

        //说明接口从2.0更新到3.0了
        String url = jsonBaseURL3 + JsonConstant.JSON_ORDER_PACKAGE;

        // 发送post请求，并接收返回结果
        String response = HttpUtil.httpPost(url, requestOrder);
        log.info("url=" + url);
        log.info("响应【同步订购】：" + response);

        //这边验证返回的是"",那么为了程序不报错给返回一个null
        if (StringUtils.isBlank(response)) {
            return null;
        }
        return JSON.parseObject(response, OrderResponse.class);
    }
}
